<template>
  <div style="padding-top: 20px;">
    <el-form :model="formValue" :rules="rules" ref="formRef" label-width="130px">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('label_pms_effective_time')">
            <div style="display: flex; align-items: center; gap: 4px;">
              <el-date-picker class="no-clear-input-text" v-model="formValue.versionStartTime" type="date"
                :placeholder="$t('label_pms_start_date')" :clearable="false" value-format="timestamp"
                :disabled="versionStartTimeDisabled"> </el-date-picker>

              <span style="color: #606266;">{{ $t('label_link') }}</span>
              <el-date-picker class="no-clear-input-text" v-model="formValue.versionEndTime" type="date"
                :placeholder="$t('label_pms_end_date')" :clearable="false" value-format="timestamp"> </el-date-picker>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="$t('label_pms_sell_price')">
        <fms-currency-choose v-model="formValue.returnMainPrice.currencyType"></fms-currency-choose>
      </el-form-item>
      <el-form-item :label="$t('label_pms_standard_service')">
        <el-table :data="formValue.returnMainPrice.standardPrices" style="margin-top: 10px; " border>
          <!--服务项名称 -->
          <el-table-column prop="serviceCode" :label="$t('label_pms_service_name')" width="180" align="center">
            <template slot-scope="scope">
              <div style="text-align: left;">{{ $t('PmsServiceCodeEnum__' + scope.row.serviceCode) }}</div>
            </template>
          </el-table-column>

          <!-- 是否收费 -->
          <el-table-column prop="needCharge" :label="$t('label_pms_need_price')" width="90" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.needCharge" active-text="" inactive-text=""> </el-switch>
            </template>
          </el-table-column>

          <!-- 收费方式 -->
          <el-table-column prop="chargeType" :label="$t('label_pms_charge_type')" width="200" align="center">
            <template slot-scope="scope">
              <ex_super_input v-model="scope.row.chargeType" type="select" enum="PmsChargeTypeEnum"
                :disabled="!scope.row.needCharge" :clearable="false"
                :listHandler="list => choosePriceType(list, scope.row)"></ex_super_input>
            </template>
          </el-table-column>

          <!-- 销售单价 -->
          <el-table-column prop="payAmount" :label="$t('label_pms_sell_money')" align="center" min-width="300">
            <template slot-scope="scope">
              <div style=" padding-left: 10px;text-align: left;">
                <el-form-item
                  v-if="scope.row.needCharge && !['EXPRESSION', 'WEIGHT_RANGE'].includes(scope.row.chargeType)"
                  :prop="'returnMainPrice.standardPrices.' + scope.$index + '.price'"
                  :rules="[{ required: true, message: $t('tip_can_no_empty'), trigger: ['blur', 'change'] }]">
                  <el-input-number v-model="scope.row.price" controls-position="right" :min="0"
                    :disabled="!scope.row.needCharge" />
                  &nbsp;
                  {{ showPriceUnitDesc(formValue.returnMainPrice.currencyType, scope.row.chargeType ?
      $t('PmsPriceUnitEnum__' + priceUnitMap[scope.row.chargeType]) : '', scope.row.chargeType) }}
                  <template v-if="scope.row.chargeType === 'PCS'">
                    &nbsp;
                    <el-switch v-model="scope.row.notNeedDestroy" />
                    {{ $t('label_destroy_collect_fees') }}
                  </template>
                </el-form-item>
                <el-button v-if="scope.row.chargeType === 'WEIGHT_RANGE'"
                  @click="weightRangeShow(scope.row, scope.$index, 'standardPrices')" type="text" size="medium">
                  <!-- 重量段配置  体积段配置 -->
                  {{ $t('label_pms_weight_range_cfg') }}
                </el-button>
                <el-button v-if="scope.row.chargeType === 'EXPRESSION'" type="text"
                  @click="showExpressionDialog(scope.row, scope.$index, 'stand')">表达式配置</el-button>


              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item :label="$t('label_pms_add_service')">
        <el-table :data="formValue.returnMainPrice.addtionalPrices" style="margin-top: 10px; " border>
          <!--服务项名称 -->
          <el-table-column prop="serviceCode" :label="$t('label_pms_service_name')" width="180" align="center">
            <template slot-scope="scope">
              <el-form-item :prop="'returnMainPrice.addtionalPrices.' + scope.$index + '.serviceCode'"
                :rules="[{ required: true, message: $t('tip_can_no_empty'), trigger: ['blur', 'change'] }]">
                <ex_super_input v-model="scope.row.serviceCode" @changeItem="(data) => serviceChange(scope.row, data)"
                  url="/fms-api/agent/AgentServiceCostRpc/selectEnable.json" type="select"
                  :option="{ label: 'serviceName', value: 'serviceCode' }"></ex_super_input>
              </el-form-item>
            </template>
          </el-table-column>

          <!-- 是否收费 -->
          <el-table-column prop="needCharge" :label="$t('label_pms_need_price')" width="90" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.needCharge" active-text="" inactive-text=""> </el-switch>
            </template>
          </el-table-column>

          <!-- 收费方式 -->
          <el-table-column prop="chargeType" :label="$t('label_pms_charge_type')" width="200" align="center">
            <template slot-scope="scope">
              <ex_super_input v-model="scope.row.chargeType" type="select" enum="PmsChargeTypeEnum"
                :disabled="!scope.row.needCharge" :clearable="false" :listHandler="() => ['ORDER', 'PCS']">
              </ex_super_input>
            </template>
          </el-table-column>

          <!-- 销售单价 -->
          <el-table-column prop="payAmount" :label="$t('label_pms_sell_money')" align="center" min-width="300">
            <template slot-scope="scope">
              <div style="padding-left: 10px;text-align: left;">
                <el-form-item
                  v-if="scope.row.needCharge && !['EXPRESSION', 'WEIGHT_RANGE'].includes(scope.row.chargeType)"
                  :prop="'returnMainPrice.addtionalPrices.' + scope.$index + '.price'"
                  :rules="[{ required: true, message: $t('tip_can_no_empty'), trigger: ['blur', 'change'] }]">
                  <el-input-number v-model="scope.row.price" controls-position="right" :min="0"
                    :disabled="!scope.row.needCharge" />
                  &nbsp;
                  {{ showPriceUnitDesc(formValue.returnMainPrice.currencyType, scope.row.chargeType ?
      $t('PmsPriceUnitEnum__' + priceUnitMap[scope.row.chargeType]) : '', scope.row.chargeType) }}
                </el-form-item>
                <el-button v-if="scope.row.chargeType === 'WEIGHT_RANGE'"
                  @click="weightRangeShow(scope.row, scope.$index, 'addtionalPrices')" type="text" size="medium">
                  <!-- 重量段配置  体积段配置 -->
                  {{ $t('label_pms_weight_range_cfg') }}
                </el-button>
                <el-button v-if="scope.row.chargeType === 'EXPRESSION'" type="text"
                  @click="showExpressionDialog(scope.row, scope.$index, '')">
                  {{ $t('label_expression_config') }}
                </el-button>
              </div>
            </template>
          </el-table-column>

          <!-- 收费方式 -->
          <el-table-column prop="chargeType" :label="$t('label_operate')" width="200" align="center">
            <template #header>
              <el-button type="primary" @click="addAdditionalServicePrice">{{ $t('label_add') }}</el-button>
            </template>
            <template slot-scope="scope">
              <ex-confirm-button :label="$t('label_delete')"
                @afterOperationDone="formValue.returnMainPrice.addtionalPrices.splice(scope.$index, 1)"></ex-confirm-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <!-- 价卡修改记录  -->
      <el-row style="margin-bottom: 100px;" v-if="formValue.id !== ''">
        <el-col>
          <el-form-item :label="$t('label_pms_price_history')">
            <el-timeline style="margin-top: 10px;" class="transprot-price-time-line">
              <el-timeline-item v-for="(item, index) in priceTagHistory" :key="index"
                :timestamp="$dateFormat(item.versionPriceTag)">
                {{ item.creator }}
                <ex-button-delete style="position: absolute; left: 220px;" message="确认切换至该版本吗？" label="切换至该版本" byAction
                  :delAction="() => switchPriceVersion(item.id)"></ex-button-delete>
              </el-timeline-item>
            </el-timeline>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 表达式弹窗 -->
    <expression-edit-dialog ref="expression" @save="saveExpression"></expression-edit-dialog>

    <pmsReturnGoodsWeightRangeCfgDialog ref="weightRangeCfgRef" @getWeightRangeFromData="getWeightRangeFromData">
    </pmsReturnGoodsWeightRangeCfgDialog>
  </div>
</template>
<script>
import FmsCurrencyChoose from '@/component/fms/fms-currency-choose.vue';
import ExpressionEditDialog from '@/component/fms/expression-edit-dialog.vue';
import pmsReturnGoodsWeightRangeCfgDialog from '@/component/pms/pms_return_goods_weight_range_cfg_dialog.vue';
export default {
  components: { FmsCurrencyChoose, ExpressionEditDialog, pmsReturnGoodsWeightRangeCfgDialog },
  mixins: [],
  data() {
    return {
      operateType: '',
      formValue: {
        tabId: '',
        id: '',
        versionId: '',
        versionName: '',
        versionStartTime: '',
        versionEndTime: '',
        versionType: '',
        status: '',
        versionTag: '',
        productId: '',
        returnMainPrice: {
          currencyType: 'CNY',
          standardPrices: [],
          addtionalPrices: []
        }
      },
      // 版本记录
      priceTagHistory: [],

      rules: {}
    };
  },
  model: {
    prop: 'inputForm',
    event: 'change'
  },
  props: {
    versionStartTimeDisabled: {
      type: Boolean,
      default: false
    },
    standardServices: {
      type: Array,
      default: () => []
    },

    additionalServices: {
      type: Array,
      default: () => []
    },

    priceUnitMap: {
      type: Object,
      default: () => { }
    },
    priceVersionId: {
      type: String,
      default: '-1'
    },
    inputForm: {
      type: Object,
      default: () => { }
    }
  },
  watch: {
    formValue: {
      // 数据变化时执行的逻辑代码
      handler(newValue, oldValue) {
        this.$emit('change', newValue);
      },
      // 开启深度监听
      deep: true
    }
  },
  mounted() {
    this.initForm();
    this.loadPriceVersionTags(this.priceVersionId);
  },
  methods: {
    initForm() {
      Object.assign(this.formValue, this.inputForm);
      // 标准费用项
      if (this.formValue.returnMainPrice.standardPrices.length === 0) {
        const standardPrices = JSON.parse(JSON.stringify(this.standardServices));
        this.$set(this.formValue.returnMainPrice, 'standardPrices', standardPrices);
      }
    },
    showPriceUnitDesc(currencyCode, unit, chargeType) {
      if (!unit) {
        if (currencyCode == 'CNY') {
          return '元';
        }
        return this.$t('CurrencyTypeEnum__' + currencyCode);
      }

      if (currencyCode == 'CNY') {
        return unit;
      }

      let tmp = unit.indexOf('元');
      if (tmp == -1) {
        return unit;
      }

      let unitDesc = this.$t('CurrencyTypeEnum__' + currencyCode);

      return unitDesc + unit.substring(1);
    },

    loadPriceVersionTags(priceVersionId) {
      // 获取单位相关映射
      this.$ajax({
        url: '/fms-api/product/PmsReturnProductVersionPriceRpc/loadPriceTags.json',
        data: { priceVersionId: priceVersionId },
        success: (res) => {
          if (res && res.data && res.data.rows) {
            this.priceTagHistory = res.data.rows;
          }
        }
      });
    },

    switchPriceVersion(priceTagId) {
      // 获取单位相关映射
      this.$ajax({
        url: '/fms-api/product/PmsReturnProductVersionPriceRpc/loadPriceTagDetail.json',
        data: {
          priceTagId: priceTagId
        },
        success: (res) => {
          if (res && res.data) {
            this.$set(this.formValue, 'returnMainPrice', res.data.returnMainPrice);
            this.$message({
              type: 'success',
              message: '切换成功'
            });
          }
        }
      });
    },
    weightRangeShow(row, index, key) {
      this.$refs.weightRangeCfgRef.show(row, index, key, 'kg');
    },
    getWeightRangeFromData(data) {
      this.$set(this.formValue.returnMainPrice[data.key], data.index, data);
    },

    // 表达式
    showExpressionDialog(item, index, type) {
      this.expressType = type;
      this.$refs['expression'].showDialog(item, index);
    },
    saveExpression(expressionForm) {
      let index = expressionForm.index;

      // console.log(expressionForm)
      if (this.expressType === 'stand') {
        this.$set(this.formValue.returnMainPrice.standardPrices[index], 'remark', expressionForm.remark);
        this.$set(this.formValue.returnMainPrice.standardPrices[index], 'expressionFunction', expressionForm.expressionFunction);
      } else {
        this.$set(this.formValue.returnMainPrice.addtionalPrices[index], 'remark', expressionForm.remark);
        this.$set(this.formValue.returnMainPrice.addtionalPrices[index], 'expressionFunction', expressionForm.expressionFunction);
      }
    },
    addAdditionalServicePrice() {
      this.formValue.returnMainPrice.addtionalPrices.push({
        serviceCode: '',
        serviceName: '',
        needCharge: true,
        chargeDays: 0,
        chargeType: 'PCS',
        priceUnit: 'YUAN_PCS',
        notNeedDestroy: true,
        price: 0,
        priceRanges: [],
        expressionFunction: '',
        remark: ''
      });
    },
    serviceChange(row, data) {
      row.serviceName = data.serviceName
    },
    choosePriceType(list, row) {
      let tmp = []
      switch (row.serviceCode) {
        case 'RETURN_RECEIVE':
          tmp = ['ORDER', 'PCS', 'WEIGHT', 'WEIGHT_RANGE']
          break;
        case 'RETURN_MEASURE':
          tmp = ['ORDER', 'WEIGHT', 'WEIGHT_RANGE']
          break;
        case 'RETURN_CHANGE_MARK':
          tmp = ['ORDER', 'PCS']
          break;
        case 'RETURN_MARK':
          tmp = ['ORDER', 'PCS']
          break;
        case 'RETURN_PHOTO':
          tmp = ['ORDER']
          break;
        case 'RETURN_VIDEO':
          tmp = ['ORDER']
          break;
        case 'RETURN_PACK':
          tmp = ['ORDER']
          break;
        case 'RETURN_PUTAWAY':
          tmp = ['ORDER', 'PCS']
          break;
        case 'RETURN_DESTROY':
          tmp = ['ORDER', 'PCS']
          break;
      }
      return tmp
    },
  }
};
</script>
<style></style>
